<?php

namespace Yolo\Config;

use Yolo\Errors\ConfigInvalidException;
use Yolo\Utils\Arr;

class ConfigManager
{
    private string $baseDir;

    private string $configSource;

    private array $config = [];

    public function __construct(string $baseDir)
    {
        $this->baseDir = realpath($baseDir);

        $this->init();
    }

    public function init(): void
    {
        if (!file_exists($this->baseDir . '/config.php')) {
            throw new ConfigInvalidException('Config file not found');
        }

        $this->configSource = file_get_contents($this->baseDir . '/config.php');
        $this->config = include $this->baseDir . '/config.php';
    }

    /**
     * Restore the config file to its original state
     * @return void
     */
    public function restore(): void
    {
        file_put_contents($this->baseDir . '/config.php', $this->configSource);
    }

    /**
     * Get the config array
     * @return array
     */
    public function getConfig(): array
    {
        return $this->config;
    }

    /**
     * Update the config array
     * @param array $config
     * @return void
     */
    public function updateConfig(array $config): void
    {
        $this->config = $config;
    }

    /**
     * Save the config to file
     * @return void
     */
    public function saveConfig(): void
    {
        file_put_contents($this->baseDir . '/config.php', "<?php\nreturn " . Arr::arrayToString($this->getConfig()) . ';');
    }
}
